﻿using Entity;
using Microsoft.AspNetCore.Http;
using ServiceCore;
using ServiceCore.Tool.NPOI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace Customer.Bussiness_Service
{

    public interface Ireplenishment_service
    {
        /// <summary>
        /// 获取销售查询的用户列表
        /// </summary>
        /// <returns></returns>
        ResultListModel<out_of_stock_mch_item> get_out_of_stock_pagelist(out_of_stock_mch_search query);

        /// <summary>
        /// 获取机器缺货信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<get_out_of_stock_details_item> get_out_of_stock_details_pagelist(get_out_of_stock_detials_query query);
        /// <summary>
        /// 导出机器缺货信息
        /// </summary>
        /// <param name="query"></param>
        void out_of_stock_details_down(get_out_of_stock_detials_query query);
        /// <summary>
        /// 查询补货记录列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<replenishment_record_list_item> get_replenishment_record_pagelist(replenishment_record_query query); 
        /// <summary>
        /// 获取单次补货详情列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<replenishment_record_details> get_replenishment_record_details_pagelist(replenishment_record_details_query query);
        /// <summary>
        ///  查询补货详情
        /// </summary>
        /// <param name="query"></param>
        void replenishment_record_details_down(replenishment_record_details_query query);
        ResultObjModel get_kid_user();
    }
    public class replenishment_service : Ireplenishment_service
    {
        private readonly IToole_DI _tool;
        private readonly INpoi_service _excelservice;
        private readonly IHttpContextAccessor _context;

        public replenishment_service(IToole_DI Tool, INpoi_service Excelservice, IHttpContextAccessor Context)
        {
            _tool = Tool;
            _excelservice = Excelservice;
            _context = Context;
        } 
        /// <summary>
        /// 获取销售查询的用户列表
        /// </summary>
        /// <returns></returns>
        public ResultListModel<out_of_stock_mch_item> get_out_of_stock_pagelist(out_of_stock_mch_search query)
        {
            return CoreStartDo.ResultAction<ResultListModel<out_of_stock_mch_item>>(result =>
            {

                string sql = "select  " +
                            " m.Id as mch_id, " +
                            " m.Name as mch_name, " +
                            " m.sn as mch_sn, " +
                            " d.* " +
                            "  from mch m " +
                            " left " +
                            "  join (select " +
                            " a.MchId, " +
                            " sum(a.maxcount) as max_stock_count, " +
                            " sum(a.count) as now_stock_count, " +
                            " sum(a.maxcount) - sum(a.count) as out_of_stock_count, " +
                            " count(Id) as slot_count,  " +
                            " count(case when maxcount > count then 1 end) as out_of_stock_slot_count, " +
                            " count(case when maxcount > a.ShortageThreshold then 1 end) as need_alert_count " +
                            "  from slot a where a.SlotStateId=22001 group by a.MchId) d on m.Id = d.MchId";
                string where = " where  m.BaseUserId=@baseuserid and out_of_stock_slot_count>0";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.baseuserid = _tool.di_user.RK_USER.BaseUserId;
                if (!string.IsNullOrWhiteSpace(query.mchname))
                {
                    where += " and m.Name like @mchname";
                    query_dy.mchname = $"%{query.mchname}%";
                } 
                string orderby = "out_of_stock_count";
                string sort = "asc";
                if (query.sort_func.HasValue)
                {
                    switch(query.sort_func.Value)
                    {

                        case out_of_stock_mch_sort_func.缺货货道数正序:
                            orderby = "out_of_stock_count";
                            sort = "asc";
                            break;
                        case out_of_stock_mch_sort_func.缺货货道数倒序:
                            orderby = "out_of_stock_count";
                            sort = "desc";
                            break;
                        case out_of_stock_mch_sort_func.缺货总数正序:
                            orderby = "out_of_stock_count";
                            sort = "asc";
                            break;
                        case out_of_stock_mch_sort_func.缺货总数倒序:
                            orderby = "out_of_stock_count";
                            sort = "desc"; 
                            break;
                        case out_of_stock_mch_sort_func.达到预警货道数正序:
                            orderby = "need_alert_count";
                            sort = "asc";
                            break;
                        case out_of_stock_mch_sort_func.达到预警货道数倒序:
                            orderby = "need_alert_count";
                            sort = "desc";
                            break;
                        default:
                            break; 
                    }
                } 
                ResultListModel<out_of_stock_mch_item> result_pagelist = _tool.di_db.GetRKPageList<out_of_stock_mch_item>(sql, where, orderby, query_dy, query.IsPage, query.page, query.pagesize, sort); 
                return result_pagelist;
            });
        } 
        /// <summary>
        /// 获取机器缺货信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<get_out_of_stock_details_item> get_out_of_stock_details_pagelist(get_out_of_stock_detials_query query)
        {
            return CoreStartDo.ResultAction<ResultListModel<get_out_of_stock_details_item>>(result =>
            {
                if (string.IsNullOrWhiteSpace(query.mch_id))
                {
                    result.code = 1;
                    result.msg = "机器ID不能为空";
                    return result;
                } 
                string sql = "select * from slot";
                string where = " where  mchid=@mch_id and SlotStateId=22001";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.mch_id = query.mch_id;
                if (!string.IsNullOrWhiteSpace(query.product_name))
                {
                    where += " and productname like @product_name";
                    query_dy.product_name = $"%{query.product_name}%";
                } 
                if (query.searchtype.HasValue)
                {
                    switch (query.searchtype.Value)
                    {
                        case search_details_enum.只看缺货货道:
                            where += " and count<maxcount";
                            break;
                        case search_details_enum.只看达到预警值货道:
                            where += " and count<ShortageThreshold";
                            break;
                        case search_details_enum.全部货道:
                        default:
                            break;
                    }
                }
                ResultListModel<get_out_of_stock_details_item> result_pagelist = _tool.di_db.GetRKPageList<get_out_of_stock_details_item>(sql, where, "[index]", query_dy, query.IsPage, query.page, query.pagesize, "asc");
                return result_pagelist;
            });
        } 
        /// <summary>
        /// 导出货道详情
        /// </summary>
        public void out_of_stock_details_down(get_out_of_stock_detials_query query)
        {
            query.IsPage = false;
            var listresult = get_out_of_stock_details_pagelist(query);
            Mch mch = _tool.di_db.Get_rk_List<Mch>("select top 1 * from mch where Id=@Id", new { Id = query.mch_id }).FirstOrDefault();
            string title = $"{DateTime.Now.ToString("yyyy年MM月dd日HH时mm分")}_{mch.Name}_货道详情.xlsx";
            _excelservice.ExcelExportService(title, listresult.rows, dosomething: fs =>
            {
                _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
                _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
                int bufferSize = Convert.ToInt32(fs.Length);
                byte[] buffer;
                buffer = new byte[bufferSize];
                int currentRead = fs.Read(buffer, 0, bufferSize);
                _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
                _context.HttpContext.Response.Body.Flush();
            });
        }
         
        /// <summary>
        /// 查询补货记录列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<replenishment_record_list_item> get_replenishment_record_pagelist(replenishment_record_query query) {
            return CoreStartDo.ResultAction<ResultListModel<replenishment_record_list_item>>(result =>
            {
           
                string sql = "select a.*,b.UserName,c.* from replenishment_record a";
                sql += " left join (select record_id as groupby_record_id,sum(a.reduce_count) as total_reduce_count,sum(a.plus_count) as total_plus_count from replenishment_record_details a group by a.record_id) c on a.record_id = c.groupby_record_id";
                sql += " left join [user] b on a.userid=b.Id";
                string where = " where  a.baseuserid=@baseuserid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.baseuserid = _tool.di_user.RK_USER.BaseUserId;
                if (!string.IsNullOrWhiteSpace(query.mch_name))
                {
                    where += " and a.mch_name like @mch_name";
                    query_dy.mch_name = $"%{query.mch_name}%";
                }
                if (!string.IsNullOrWhiteSpace(query.userid))
                {
                    where += " and a.userid = @userid";
                    query_dy.userid = query.userid;
                }
                DateTime starttime;
                if (DateTime.TryParse(query.start_time, out starttime))
                {
                    where += " and a.add_time >= @end_time";
                    query_dy.end_time = starttime;
                }
                DateTime endtime;
                if (DateTime.TryParse(query.end_time,out endtime))
                {
                    where += " and a.add_time <= @end_time";
                    query_dy.end_time = endtime;
                }
                ResultListModel<replenishment_record_list_item> result_pagelist = _tool.di_db.GetRKPageList<replenishment_record_list_item>(sql, where, "a.add_time", query_dy, query.IsPage, query.page, query.pagesize);
                return result_pagelist;
            });
        }

        /// <summary>
        /// 获取补货详情分页列表
        /// </summary>
        /// <returns></returns>
        public ResultListModel<replenishment_record_details> get_replenishment_record_details_pagelist(replenishment_record_details_query query) {
            return CoreStartDo.ResultAction<ResultListModel<replenishment_record_details>>(result =>
            {
                if (string.IsNullOrWhiteSpace(query.record_id))
                {
                    result.code = 1;
                    result.msg = "补货记录ID未知";
                    return result;
                }
                string sql = "select * from replenishment_record_details";
                string where = " where  record_id=@record_id";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.record_id = query.record_id; 
                if (!string.IsNullOrWhiteSpace(query.product_name))
                {
                    where += " and  product_name like @product_name";
                    query_dy.product_name = $"%{query.product_name}%";
                }
                if (query.searchtype.HasValue)
                {
                    switch (query.searchtype.Value)
                    {
                        case search_record_details_enum.只看减少库存:
                            where += " and show_count<0";
                            break;
                        case search_record_details_enum.只看增加库存:
                            where += " and show_count>0";
                            break;
                        case search_record_details_enum.全部:
                        default:
                            break;
                    }
                } 
                ResultListModel<replenishment_record_details> result_pagelist = _tool.di_db.GetRKPageList<replenishment_record_details>(sql, where, "slot_index", query_dy, query.IsPage, query.page, query.pagesize, "asc");
                return result_pagelist;
            });
        }

        /// <summary>
        /// 导出货道详情
        /// </summary>
        public void replenishment_record_details_down(replenishment_record_details_query query)
        {
            query.IsPage = false;
            var listresult = get_replenishment_record_details_pagelist(query);
            replenishment_record record = _tool.di_db.Get_rk_List<replenishment_record>("select top 1 * from replenishment_record where record_id=@record_id", new { query.record_id }).FirstOrDefault();
            User umod = _tool.di_db.Get_rk_List<User>("select top 1 * from [User] where Id=@Id", new { Id = record.userid }).FirstOrDefault();

            string title = $"{record.add_time.ToString("yyyy年MM月dd日HH时mm分")}_{umod.UserName}_{umod.Name}_{record.mch_name}_补货详情.xlsx";
            _excelservice.ExcelExportService(title, listresult.rows, dosomething: fs =>
            {
                _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
                _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
                int bufferSize = Convert.ToInt32(fs.Length);
                byte[] buffer;
                buffer = new byte[bufferSize];
                int currentRead = fs.Read(buffer, 0, bufferSize);
                _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
                _context.HttpContext.Response.Body.Flush();
            });
        }
        /// <summary>
        /// 获取当前登录用户自己的账号信息以及子账号信息
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_kid_user()
        {
            return CoreStartDo.ResultAction(result =>
            {
                var user_list = _tool.di_db.Get_rk_List<User>("select * from [user] where id=@self_userid or ParentId=@self_userid and IsDelete=0", new
                {
                    self_userid = _tool.di_user.RK_USER.Id
                });
                result.code = 0;
                result.msg = "success";
                result.data = from o in user_list
                              select new
                              {
                                  o.Id,
                                  o.Name,
                                  o.UserName
                              };
                return result;
            });
        }
    }
}
